# -*- coding: utf-8 -*-

from machine import Pin, Timer

class zmkeys():

    def __init__(self, goip, callfunc):
        self.__callfunc = callfunc
        self.button = Pin(goip, Pin.IN)
        self.button_default_value = self.button.value()
        self.button_down_int = 0
        self.button_isdown = False

        self.enable_time = 3
        self.enable_is = False
        self.tim = Timer(-1)

    def __callfunc(self):
        pass

    def __keyInitOne_run(self,e):
        self.__callfunc()

    def __keyParaInit_run(self,e):
        val = self.button.value()
        if int(self.button_default_value) != int(val):
            self.button_down_int += 1
            if self.button_down_int >= self.enable_time and self.enable_is is False:
                self.enable_is = True
                self.__callfunc()
        else:
            self.button_down_int = 0
            self.enable_is = False
            self.button_isdown = False
            self.tim.deinit()

    # 短按按键
    def keyInitOne(self):
        self.button.irq(trigger=Pin.IRQ_FALLING, handler=self.__keyInitOne_run)

    # 长按按键
    # downtiem -- 按下多少秒钟触发
    def keyParaInit(self, downtiem=3):
        self.enable_time = downtiem
        def keyParaRun(e):
            val = self.button.value()
            if int(self.button_default_value) != int(val) and self.button_isdown is False:
                self.button_isdown = True
                self.tim.init(period=1000, mode=Timer.PERIODIC, callback=self.__keyParaInit_run)

        self.button.irq(trigger=Pin.IRQ_FALLING, handler=keyParaRun)